package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aixingfu.sports.MVP.contract.CacheCardUpgradeContract;
import com.aixingfu.sports.MVP.contract.DiscountContract;
import com.aixingfu.sports.MVP.contract.MemberCardMoneyContract;
import com.aixingfu.sports.MVP.contract.UpgradeContract;
import com.aixingfu.sports.MVP.presenter.CacheCardUpgradePresenter;
import com.aixingfu.sports.MVP.presenter.DiscountPresenter;
import com.aixingfu.sports.MVP.presenter.MemberCardSurplusMoneyPresenter;
import com.aixingfu.sports.MVP.presenter.UpgradePresenter;
import com.aixingfu.sports.Model.CacheCardUpgradeModel;
import com.aixingfu.sports.Model.DiscountModel;
import com.aixingfu.sports.Model.MemberCardSurplusMoneyModel;
import com.aixingfu.sports.Model.UpgradeModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.view.PopUpgradeCheckChooseID;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.view.RxToast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

//升级
@Route(path = "/main/UpgradeActivity")
public class UpgradeActivity extends BaseActivity implements UpgradeContract.MyView, DiscountContract.MyView, CacheCardUpgradeContract.MyView, MemberCardMoneyContract.MyView {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_card_name)
    TextView tvCardName;
    @BindView(R.id.tv_remaining_days)
    TextView tvRemainingDays;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_card_code)
    TextView tvCardCode;
    @BindView(R.id.tv_due_time)
    TextView tvDueTime;
    @BindView(R.id.tv_upgrade_mode)
    TextView tvUpgradeMode;
    @BindView(R.id.ll_upgrade_mode)
    LinearLayout llUpgradeMode;
    @BindView(R.id.tv_card_type_name)
    TextView tvCardTypeName;
    @BindView(R.id.ll_card_type_name)
    LinearLayout llCardTypeName;
    @BindView(R.id.tv_card_price)
    TextView tvCardPrice;
    @BindView(R.id.tv_original_amount)
    TextView tvOriginalAmount;
    @BindView(R.id.tv_card_discount)
    TextView tvCardDiscount;
    @BindView(R.id.ll_card_discount)
    LinearLayout llCardDiscount;
    @BindView(R.id.ed_converted_amount)
    EditText edConvertedAmount;
    @BindView(R.id.tv_use_time)
    TextView tvUseTime;
    @BindView(R.id.ed_reimbursement_amount)
    EditText edReimbursementAmount;
    @BindView(R.id.ed_remarks)
    EditText edRemarks;
    @BindView(R.id.ed_card_type_price)
    EditText edCardTypePrice;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    private UpgradePresenter upgradePresenter;
    private DiscountPresenter discountPresenter;
    private String upgradeMode, cardTypeName, cardTypePrice, orignalAmount, cardDiscount, userTime, reimbursementAmount, remarks;
    private String username, mobile, card_name, card_number, create_at, invalid_time, venue_id, oldCardCategory, oldCardId, memberCard_id, member_id, amount_money;
    private String convertedAmount = "0";
    private PopupWindowCheckChoose mPopup;
    private ArrayList<String> mList = new ArrayList();
    private List<UpgradeModel.DataBean.CategoryListBean> catgoryList;
    private PopUpgradeCheckChooseID popUpgradeCheckChooseID;
    private String cardTypeId;
    private CacheCardUpgradePresenter cacheCardUpgradePresenter;
    private String originalPrice;
    private MemberCardSurplusMoneyPresenter memberCardSurplusMoneyPresenter;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_upgrade;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/UpgradeActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        tvTitle.setText("卡种升级");
        Bundle bundle = getIntent().getExtras();
        username = bundle.getString("username", "");
        mobile = bundle.getString("mobile", "");
        card_name = bundle.getString("card_name", "");
        card_number = bundle.getString("card_number", "");
        create_at = bundle.getString("create_at", "");
        invalid_time = bundle.getString("invalid_time", "");
        venue_id = bundle.getString("venue_id", "");
        oldCardCategory = bundle.getString("oldCardCategory", "");
        oldCardId = bundle.getString("oldCardId", "");
        memberCard_id = bundle.getString("memberCard_id", "");
        member_id = bundle.getString("member_id", "");
        amount_money = bundle.getString("amount_money", "");
        upgradePresenter = new UpgradePresenter();
        upgradePresenter.attachView(this);
        MoneyEditUtils.afterDotTwo(edCardTypePrice);
        getOldUpgrade();

        discountPresenter = new DiscountPresenter();
        discountPresenter.attachView(this);
        cacheCardUpgradePresenter = new CacheCardUpgradePresenter();
        cacheCardUpgradePresenter.attachView(this);
        memberCardSurplusMoneyPresenter = new MemberCardSurplusMoneyPresenter();
        memberCardSurplusMoneyPresenter.attachView(this);
        mList = getPopList();
        mPopup = new PopupWindowCheckChoose(UpgradeActivity.this, mList);
        mPopup.setTagTxt("请选择升级方式")//设置顶部title的内容
                .setButtomTxt("取消")//设置底部按钮内容
                .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
        //单选
        mPopup.setOnEventLisenter(positionList -> {
            mPopup.dismiss();
            tvUpgradeMode.setText(mList.get(positionList.get(0)));
            upgradeMode = mList.get(positionList.get(0));
            if ("期限升级".equals(upgradeMode)) {
                tvContent.setText("按老卡办卡时间为升级后的新卡开始时间");
                getMemberCardMoney();
                edReimbursementAmount.setText("");
            } else if ("折现升级".equals(upgradeMode)) {
                tvContent.setText("按当前时间为升级后的新卡开始时间");
                edConvertedAmount.setText("");
                edReimbursementAmount.setText("");
            }
        });
        setContent();
        edCardTypePrice.addTextChangedListener(editclick);
        edConvertedAmount.addTextChangedListener(editclick);
        getMemberCardMoney();
    }

    public void setContent() {
        try {
            tvMemberName.setText("会员姓名：" + username);
            tvCardName.setText("卡种名称：" + card_name);
            tvPhone.setText("手机号：" + mobile);
            tvCardCode.setText("会员卡号：" + card_number);
            long curTimeMills = RxTimeTool.getCurTimeMills() / 1000;
            long remainTime = Long.parseLong(invalid_time) - curTimeMills;
            String time = String.valueOf(remainTime / 60 / 60 / 24);
            tvRemainingDays.setText("剩余天数：" + time + "天");
            tvDueTime.setText("到期时间：" + RxTimeTool.stampToDate(invalid_time));
            tvOriginalAmount.setText(amount_money);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("期限升级");
        popList.add("折现升级");
        return popList;
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected void beforeInit() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_back, R.id.ll_upgrade_mode, R.id.ll_card_type_name, R.id.ll_card_discount, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.ll_upgrade_mode:
                hideIputKeyboard();
                if (mPopup != null) {
                    mPopup.showPop(tvUpgradeMode);
                }
                break;
            case R.id.ll_card_type_name:
                hideIputKeyboard();
                if (popUpgradeCheckChooseID != null) {
                    popUpgradeCheckChooseID.showPop(tvCardTypeName);
                }
                break;
            case R.id.ll_card_discount:
                break;
            case R.id.tv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_next:
                upgradeMode = tvUpgradeMode.getText().toString();
                cardTypeName = tvCardTypeName.getText().toString();
                cardTypePrice = edCardTypePrice.getText().toString();
                orignalAmount = tvOriginalAmount.getText().toString();
                cardDiscount = tvCardDiscount.getText().toString();
                convertedAmount = edConvertedAmount.getText().toString();
                userTime = tvUseTime.getText().toString();
                reimbursementAmount = edReimbursementAmount.getText().toString();
                remarks = edRemarks.getText().toString();
                if (TextUtils.isEmpty(upgradeMode)) {
                    RxToast.normal(UpgradeActivity.this, "请选择升级方式").show();
                } else if (TextUtils.isEmpty(cardTypeName)) {
                    RxToast.normal(UpgradeActivity.this, "请选择卡种名称").show();
                } else if (TextUtils.isEmpty(cardTypePrice)) {
                    RxToast.normal(UpgradeActivity.this, "请输入卡种价格").show();
                } else if (TextUtils.isEmpty(orignalAmount)) {
                    RxToast.normal(UpgradeActivity.this, "原价金额不能为空").show();
                } else if (TextUtils.isEmpty(convertedAmount)) {
                    RxToast.normal(UpgradeActivity.this, "请输入折算金额").show();
                } else if (TextUtils.isEmpty(userTime)) {
                    RxToast.normal(UpgradeActivity.this, "使用期限不能为空").show();
                } else if (TextUtils.isEmpty(reimbursementAmount)) {
                    RxToast.normal(UpgradeActivity.this, "请输入补交金额").show();
                } else {
                    getCacheCardUpgrade();
                }
                break;
        }
    }

    public void getOldUpgrade() {
        if (upgradePresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("oldCardCategory", oldCardCategory);
            map.put("venue_id", venue_id);
            map.put("memberCard_id", memberCard_id);
            map.put("member_id", member_id);
            upgradePresenter.getUpgrade(map);
        }
    }

    public void getMemberCardMoney() {
        if (memberCardSurplusMoneyPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("memberCardId", memberCard_id);
            memberCardSurplusMoneyPresenter.getMemberCardSurplusMoney(map);
        }
    }

    public void getCacheCardUpgrade() {
        if (cacheCardUpgradePresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            if ("期限升级".equals(upgradeMode)) {
                map.put("type", "1");
            } else if ("折现升级".equals(upgradeMode)) {
                map.put("type", "2");
            }
            map.put("old_card_id", memberCard_id);
            map.put("sell_price", cardTypePrice);
            map.put("discount", cardDiscount);
            map.put("new_category_id", cardTypeId);
            map.put("net_price", reimbursementAmount);
            map.put("member_id", member_id);
            map.put("surplus_price", convertedAmount);
            cacheCardUpgradePresenter.getCacheCardUpgrade(map);
        }
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setMemberCardSurplusMoney(MemberCardSurplusMoneyModel data) {
        if (data.getCode() == 1) {
            try {
                edConvertedAmount.setText("" + data.getData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setFailed(String msg) {
        RxToast.normal(UpgradeActivity.this, msg).show();
    }

    @Override
    public void setCacheCardUpgrade(CacheCardUpgradeModel data) {
        if (data.getCode() == 1) {
            ARouter.getInstance().build("/main/PaymentUpgradeActivity").withString("member_id", member_id).navigation();
            RxToast.normal(UpgradeActivity.this, data.getMessage()).show();
        } else {
            RxToast.normal(UpgradeActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setDiscount(DiscountModel data) {

    }

    @Override
    public void setUpgrade(UpgradeModel data) {
        if (data.getCode() == 1) {

            catgoryList = data.getData().getCategory_list();
            popUpgradeCheckChooseID = new PopUpgradeCheckChooseID(UpgradeActivity.this, catgoryList);
            popUpgradeCheckChooseID.setTagTxt("请选择卡种")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popUpgradeCheckChooseID.setOnEventLisenter(positionList -> {
                upgradeMode = tvUpgradeMode.getText().toString();
                popUpgradeCheckChooseID.dismiss();
                tvCardTypeName.setText(catgoryList.get(positionList.get(0)).getCard_name());
                cardTypeId = catgoryList.get(positionList.get(0)).getId();
//                String original_price = catgoryList.get(positionList.get(0)).getOriginal_price();
//                if (TextUtils.isEmpty(original_price)) {
//                    tvOriginalAmount.setText("");
//                } else {
//                    tvOriginalAmount.setText(catgoryList.get(positionList.get(0)).getOriginal_price() + "");
//                }
//                tvUseTime.setText(catgoryList.get(0).get);
                if ("期限升级".equals(upgradeMode)) {
                    long day = catgoryList.get(positionList.get(0)).getDuration().getDay();
                    long dayTime = Long.parseLong(create_at) + day * 24 * 60 * 60;
                    tvUseTime.setText(RxTimeTool.stampToDate(create_at) + "到" + RxTimeTool.stampToDate(String.valueOf(dayTime)));
//                    edConvertedAmount.setFocusable(false);//设置输入框可聚集
//                    edConvertedAmount.setFocusableInTouchMode(false);//设置触摸聚焦
                } else if ("折现升级".equals(upgradeMode)) {
                    setDay(catgoryList.get(0).getDuration().getDay());
                    tvUseTime.setText(getDay() + "到" + setDay(catgoryList.get(positionList.get(0)).getDuration().getDay()));
                    edConvertedAmount.clearFocus();
//                    edConvertedAmount.setFocusable(true);//设置输入框可聚集
//                    edConvertedAmount.setFocusableInTouchMode(true);//设置触摸聚焦
                }
            });
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.mipmap.touxiang)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
            Glide.with(UpgradeActivity.this)
                    .load(data.getData().getMember_info().getAvatar_url())
                    .apply(options)
                    .into(ivHead);
        }
    }

    public String getDay() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        String dayTime = sf.format(c.getTime());
        return dayTime;
    }

    public String setDay(int day) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, day);
        String format = sf.format(cal.getTime());
        return format;
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    private final TextWatcher editclick = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        //一般我们都是在这个里面进行我们文本框的输入的判断，上面两个方法用到的很少
        @Override
        public void afterTextChanged(Editable s) {
            try {
                convertedAmount = edConvertedAmount.getText().toString();
                if (TextUtils.isEmpty(convertedAmount)) {
                    convertedAmount = "0";
                } else {
                    convertedAmount = edConvertedAmount.getText().toString();
                }
                String money = edCardTypePrice.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    money = "0";
                } else {
                    money = edCardTypePrice.getText().toString();
                }
                double a = Double.parseDouble(money);
                double v = Double.parseDouble(convertedAmount);
                String v1 = String.valueOf(a - v);
                edReimbursementAmount.setText(v1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }

}
